<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

Class Muser extends MY_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function saveinfoDB()
    {
        $id = $this->getParamInt('id');
//        $username     = $this->getParamInt('username');
        $fullname = $this->getParamString('fullname');
        $birthday = $this->getParamString('birthday');
        $address = $this->getParamString('address');
//        $mobile = $this->getParamString('mobile');
        $email = $this->getParamString('email');
        $job_id = $this->getParamInt('job_id');
        If (in_array($fullname, array(null, '')) || in_array($email, array(null, '', '0')))
        {
            return (object) array('status' => 210, 'description' => 'Full name và email không được để trống');
        }
//        $gender     = $this->getParamInt('gender');
        //$job        = $this->getParamString('job');
        //$agegroup_id = $this->getParamInt('agegroup_id'); // 1->5
//		$province_id = $this->getParamString('province_id');
//		$district_id = $this->getParamString('district_id');	
        //Check xem số điện thoại đã có người dùng chưa
//        if (!in_array($mobile, array(null, '')))
//        {
//            $checkMobile = $this->db->query("SELECT * FROM member WHERe id != '$id' AND mobile = '$mobile' ")->num_rows();
//            if ($checkMobile > 0 || !$this->numeric($mobile))
//                return (object) array('status' => 203, 'description' => 'Số điện thoại đã có người dùng');
//            if (!$this->numeric($mobile))
//                return (object) array('status' => 207, 'description' => 'Số điện thoại phải là số');
//        }

        //Check xem email đã có người dùng chưa
        if (!in_array($email, array(null, '')))
        {
            $checkEmail = $this->db->query("SELECT * FROM member WHERe id != '$id' AND email = '$email' ")->num_rows();
            if ($checkEmail > 0)
                return (object) array('status' => 204, 'description' => 'Email đã có người dùng');
            if ($this->valid_email($email))
                return (object) array('status' => 208, 'description' => 'Email không hợp lệ');
        }
        
        //Check xem job đã chuẩn chưa 
        if (!in_array($job_id, array(null, '')))
        {
            $checkJob = $this->db->query("SELECT * FROM vn_job WHERe id = '$job_id'")->num_rows();
            if ($checkJob == 0)
                return (object) array('status' => 205, 'description' => 'Nghề nghiệp không hợp lệ');
        }

        //Check xem date đã chuẩn chưa
        if (!in_array($birthday, array(null, '')))
        {
            $checkDate = $this->checkDate($birthday);
            if ($checkDate == false)
                return (object) array('status' => 206, 'description' => 'Birthday không hợp lệ');
            list($dd, $mm, $yyyy) = explode('/', $birthday);
            $birthday = $yyyy . '-' . $mm . '-' . $dd;
        }
        $data = array(
//            'username' => $username,
            'fullname' => $fullname,
            'dateofbirth' => $birthday,
            'address' => $address,
//            'mobile' => $mobile,
            'email' => $email,
            'job_id' => $job_id,
//				'dateofbirth'	=> $birthday,
//                //'agegroup_id' => $agegroup_id,
//				'job_id' => $job_id,
//				'province_id' => $province_id,
//				'district_id' => $district_id			
        );
        $this->db->update('member', $data, "id = '" . $id . "'");
        if ($this->db->affected_rows() > 0)
        {
            return (object) array('status' => 200, 'description' => 'Cập nhật thành công');
        } else
        {
            return (object) array('status' => 201, 'description' => 'Không có cập nhật mới');
        }
    }

	public function saveinfothefirstDB()
    {
		$id = $this->getParamInt('id');
        $fullname   = $this->getParamString('fullname');
		$email = $this->getParamString('email');
		$dateofbirth = $this->getParamString('dateofbirth');
		$mobile = $this->getParamString('mobile');
		$province_id = $this->getParamInt('province_id');
		if( in_array($id,array('',null)) || in_array($fullname,array('',null)) || in_array($email,array('',null)) || in_array($dateofbirth,array('',null)) || in_array($mobile,array('',null)) || in_array($province_id,array('',null))  ){
			return (object)array('status' => 201, 'description' => 'Điền thiếu thông tin');
		}
		if( $this->valid_email($email) == 1 ){
			return (object)array('status' => 202, 'description' => 'Định dạng email không chính xác');
		}
		if( strlen($mobile) < 10 || strlen($mobile) > 12 ){
			return (object)array('status' => 203, 'description' => 'Định dạng số điện thoại không chính xác');
		}
		if( $this->db->query('SELECT id FROM member WHERE email = "'.$email.'" AND id != '.$id.' ')->num_rows() > 0 ){
			return (object)array('status' => 204, 'description' => 'Email đã tồn tại trong hệ thống');
		}
		if( $this->db->query('SELECT id FROM member WHERE ( username = "'.$mobile.'" || mobile = "'.$mobile.'" ) AND id != '.$id.' ')->num_rows() > 0 ){
			return (object)array('status' => 205, 'description' => 'Số điện thoại đã tồn tại trong hệ thống');
		}
        $data = array(
				'fullname'  => $fullname,
				'email' => $email,
				'dateofbirth' => $dateofbirth,
				'mobile' => $mobile,
				'update_first' => 1,
				'province_id' => $province_id
				);
        $this->db->update('member', $data, "id = '".$id."'");
        if ($this->db->affected_rows() > 0)
        {
            return (object)array('status' => 200, 'description' => 'Cập nhật thành công');
        }else{
			return (object)array('status' => 204, 'description' => 'Không có cập nhật mới');
		} 
    }
	
	
    public function loginUserEmail()
    {
        $uname = $this->getParamString('username');
        $upass = $this->getParamString('password');
        $pass_encode = md5(md5($uname) . md5($upass));

        $sql = $this->db->query("SELECT * FROM member WHERE username = '" . strtolower($uname) . "' AND password = '" . $pass_encode . "' ");
        if ($sql->num_rows() > 0)
        {
            $data_ = $sql->row();
            $data_->password = null;

            /* if( !in_array($data_->job_id, array('',null)) ){
              $meme = $this->db->query('SELECT name FROM vn_job WHERE id = '.$data_->job_id);
              if( $meme->num_rows() == 0){
              $data_->job_name = 'Đang cập nhật';
              }else{
              $data_->job_name = $meme->row()->name;
              }
              }else{
              $data_->job_name = 'Đang cập nhật';
              } */





            $active = $data_->active;
            if ($active == 0)
            {
                return (object) array('status' => 203, 'description' => 'Tài khoản chưa được kích hoạt');
            } else if ($active == 2)
            {
                return (object) array('status' => 204, 'description' => 'Tài khoản của bạn đang bị khóa');
            } else
            {
                return (object) array('status' => 200, 'content' => $this->getInfoUser($data_->id), 'description' => 'Đăng nhập thành công');
            }
        } else
        {
            return (object) array('status' => 201, 'description' => 'Mật khẩu không đúng. Vui lòng thử lại.');
        }
    }

    public function loginMobileDb($mobile, $upass)
    {
//        $mobile = $this->getParamString('mobile');
//        $upass = $this->getParamString('password');
        if ($mobile == null || !$this->numeric($mobile))
            return (object) array('status' => 202, 'description' => 'Số điện thoại không đúng. Vui lòng thử lại.');

        //$sql = $this->db->query("SELECT * FROM member WHERE mobile = '".$mobile."'");
        $sql = $this->db->query("SELECT m.*,vn_job.name as name_job,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id "
                . "LEFT JOIN vn_job ON m.job_id = vn_job.id "
                . " WHERE m.mobile = '$mobile' ");

        if ($sql->row()->mobile != null)
        {
            $data_ = $sql->row();
            $pass_encode = md5(md5($data_->username) . md5($upass));
//             var_dump($pass_encode,$data_->username,$upass);die;
            if ($pass_encode == $data_->password)
            {
                $active = $data_->active;
                if ($active == 0)
                {
                    return (object) array('status' => 203, 'description' => 'Tài khoản chưa được kích hoạt');
                } else if ($active == 2)
                {
                    return (object) array('status' => 204, 'description' => 'Tài khoản của bạn đang bị khóa');
                } else
                {
                    $data_->password = '';
                    return (object) array('status' => 200,
//                        'content' => $this->getInfoUser($data_->id), 
                                'userInfo' => $data_,
                                'description' => 'Đăng nhập thành công');
                }
            } else
            {
                return (object) array('status' => 201, 'description' => 'Mật khẩu không đúng. Vui lòng thử lại.');
            }
        } else
        {
            return (object) array('status' => 202, 'description' => 'Số điện thoại không tồn tại');
        }
    }

    public function loginFacebookDb($fbid)
    {
//        $fbid = $this->getParamString('fbid');
        if ($fbid == NULL)
            return (object) array('status' => 201, 'description' => 'Id không đúng. Vui lòng thử lại.');
        $sql = $this->db->query("SELECT m.*,vn_job.name as name_job,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id "
                . "LEFT JOIN vn_job ON m.job_id = vn_job.id "
                . "WHERE m.fbid = '$fbid'");
        if ($sql->row()->fbid != null)
        {
            $userInfo = $sql->row();
            if ($userInfo->active == 2)
            {
                return (object) array('status' => 204, 'description' => 'Tài khoản đang bị khóa.');
            }
            $userInfo->password = '';
            return (object) array('status' => 200,
//                        'content' => $this->getInfoUser($data_->id), 
                        'userInfo' => $userInfo,
                        'description' => 'Đăng nhập thành công');
        } else
        {
            return (object) array('status' => 201, 'description' => 'Id không đúng. Vui lòng thử lại.');
        }
    }

    public function loginGoogleDb($ggid)
    {
//        $ggid = $this->getParamString('ggid');
        if ($ggid == NULL)
            return (object) array('status' => 201, 'description' => 'Id không đúng. Vui lòng thử lại.');
        $sql = $this->db->query("SELECT m.*,vn_job.name as name_job,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id "
                . "LEFT JOIN vn_job ON m.job_id = vn_job.id "
                . "WHERE m.ggid = '$ggid'");
        if ($sql->row()->ggid != null)
        {
            $userInfo = $sql->row();
            if ($userInfo->active == 2)
            {
                return (object) array('status' => 204, 'description' => 'Tài khoản đang bị khóa.');
            }
            $userInfo->password = '';
            return (object) array('status' => 200,
//                        'content' => $this->getInfoUser($data_->id), 
                        'userInfo' => $userInfo,
                        'description' => 'Đăng nhập thành công');
        } else
        {
            return (object) array('status' => 201, 'description' => 'id không đúng. Vui lòng thử lại.');
        }
    }

    public function registerMobileDb($baseurl)
    {

        //Get parameters (mobile,password,verify_password,full name)
        $mobile = $this->getParamString('mobile');
        $pass = $this->getParamString('password');
        $fullname = $this->getParamString('fullname');
        $username = $mobile;
        $pass_encode = md5(md5($username) . md5($pass));
        If (!$this->numeric($mobile) || in_array($pass, array(null, '', '0')) || in_array($fullname, array(null, '', '0')) || in_array($mobile, array(null, '', '0')))
        {
            return (object) array('status' => 201, 'description' => 'Tham số không đúng');
        }
        //Check check whether the user exists
        $check = $this->db->query('SELECT * FROM member WHERE mobile = "' . $mobile . '"')->num_rows();
        if ($check == 0)
        {
            //insert into active table
            $code = $this->generateCodeNumber(5); // code active
            $active = array(
                'phone' => $mobile,
                'code_active' => $code,
                'status' => 0,
                'username' => $username,
            );
            $this->db->insert('user_active', $active);
            $id_active = $this->db->insert_id();
            //insert into user table
            $data = array(
                'username' => $username,
                'password' => $pass_encode,
                'mobile' => $mobile,
                'fullname' => $fullname,
                'code' => $code,
                'created' => date('Y-m-d H:i:s'),
                'active' => 0,
                'id_active' => $id_active
            );
            $this->db->insert('member', $data);
//            $id_user_insert = $this->db->insert_id();
//           $this->sendActiveCode($code,$username, $fullname,$baseurl);
            return (object) array('status' => 200, 'description' => 'Đăng kí thành công');
        } else
        {
            return (object) array('status' => 202, 'description' => 'Thông tin tài khoản đã được đăng ký. Vui lòng thử lại.');
        }
    }

    public function resendCodeMobileDb()
    {
        //Check tham sô đã đúng chưa
        $mobile = $this->getParamString('mobile');
        If (!$this->numeric($mobile))
        {
            return (object) array('status' => 201, 'description' => 'Số điện thoại không hợp lệ');
        }
        //Check check whether the user exists
        $data = $this->db->query('SELECT * FROM user_active WHERE phone = "' . $mobile . '"');
        $check = $data->num_rows();
        If ($check == 0)
        {
            return (object) array('status' => 202, 'description' => 'Số điện thoại này chưa được đăng kí');
        }
        if($data->row()->number_send >=3 ) return (object) array('status' => 201, 'description' => 'Bạn chỉ gửi tối đa 3 tin nhắn 1 ngày');
        $this->db->update('user_active', array('status' => 0), "phone = '" . $mobile . "'");
        $this->db->update('member', array('active' => 0), "mobile = '" . $mobile . "'");
        return (object) array('status' => 200, 'description' => 'Gửi mã thành công');
    }

    private function checkAmountUser()
    {
        $data = $this->db->query('SELECT content, action FROM setting WHERE `action` in ("limitcoupon", "limitcode") ORDER BY id DESC')->result_object();
        $arr = array();

        foreach ($data AS $el => $le)
        {
            $exp = null;
            $exp = explode(',', $le->content);
            if ($le->action == 'limitcoupon')
            {
                $arr['form_coupon'] = $exp[0];
                $arr['to_coupon'] = $exp[1];
            } else if ($le->action == 'limitcode')
            {
                $arr['form_code'] = $exp[0];
                $arr['to_code'] = $exp[1];
            }
        }

        $countUser = $this->db->query('SELECT * FROM member')->num_rows(); // 66

        $check = array();
        if ($countUser < $arr['to_coupon'] && $countUser > $arr['form_coupon'])
        {
            $check['coupon'] = 1;
        } else
        {
            $check['coupon'] = 0;
        }

        if (($countUser > $arr['form_code']) && ($countUser < $arr['to_code']))
        {
            $check['code'] = 1;
        } else
        {
            $check['code'] = 0;
        }

        return $check;
    }

    private function sendCode($code, $username, $fullname, $gift_name)  // NHẬN QUÀ TẶNG
    {
        $data_m = json_decode($this->db->query('SELECT * FROM `options` WHERE tags = "form_email_gift" ')->row()->content);
        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => $this->_smtp_host,
            'smtp_user' => $this->_smtp_user,
            'smtp_pass' => $this->_smtp_pass,
            'mailtype' => 'html'
        );
        $this->load->library('email', $config);
        $body = "<img src='http://125.212.192.114/ggift/data/images/other/mail-header-gg.jpg' style='width: 825px;'/><br/><br/><strong>Chào " . $fullname . "!</strong> <br /><br /> " . $data_m->header . " <br>Mã quà tặng của bạn là: <b>" . $code . "</b><br />" . $data_m->content . " <br><br/><br/><img src='http://125.212.192.114/ggift/data/images/other/mail-footer-gg.jpg' style='width: 825px;'/>";
        $this->email->from($this->_smtp_user, 'G-People');
        $this->email->to($username);
        $this->email->subject('Thông báo quà tặng G-People');
        $this->email->message($body);
        if ($this->email->send())
        {
            
        }
    }

    private function sendCoupon($code, $username, $fullname)   // NHẬN MÃ VOUCHER
    {
        $data_m = json_decode($this->db->query('SELECT * FROM `options` WHERE tags = "form_email_voucher" ')->row()->content);
        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => $this->_smtp_host,
            'smtp_user' => $this->_smtp_user,
            'smtp_pass' => $this->_smtp_pass,
            'mailtype' => 'html'
        );
        $this->load->library('email', $config);
        $body = "<img src='http://125.212.192.114/ggift/data/images/other/mail-header-gg.jpg' style='width: 825px;'/><br/><br/><strong>Chào " . $fullname . "!</strong> <br /><br /> " . $data_m->header . "<br />Mã voucher quà tặng của bạn là <b>" . $code . "</b> <br />" . $data_m->content . "<br/><br/><img src='http://125.212.192.114/ggift/data/images/other/mail-footer-gg.jpg' style='width: 825px;'/>";
        $this->email->from($this->_smtp_user, 'G-People');
        $this->email->to($username);
        $this->email->subject('Thông báo mã voucher quà tặng G-People');
        $this->email->message($body);
        if ($this->email->send())
        {
            
        }
    }

    public function sendMailGift($name_gift, $username)
    {
        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => $this->_smtp_host,
            'smtp_user' => $this->_smtp_user,
            'smtp_pass' => $this->_smtp_pass,
            'mailtype' => 'html'
        );
        $this->load->library('email', $config);
        $body = "<img src='http://125.212.192.114/ggift/data/images/other/mail-header-gg.jpg' style='width: 825px;'/><br/><br/><strong>Chào " . $username . "!</strong> <br /><br /> Chúc mừng " . $username . " đã sử dụng ứng dụng G-People. Bạn đã nhận được món quà từ chương trình của chúng tôi là: " . $name_gift . " .<br /><br /> Cám ơn bạn !<br/><br/><img src='http://125.212.192.114/ggift/data/images/other/mail-footer-gg.jpg' style='width: 825px;'/>";

        $this->email->from($this->_smtp_user, 'G-People');
        $this->email->to($username);
        $this->email->subject('Thông báo mã voucher quà tặng G-People');
        $this->email->message($body);

        if ($this->email->send())
        {
            
        }
    }

    /* send email active account */

    private function sendActiveCode($code, $username, $fullname, $baseurl)
    {
        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => $this->_smtp_host,
            'smtp_user' => $this->_smtp_user,
            'smtp_pass' => $this->_smtp_pass,
            'mailtype' => 'html'
        );

        $this->load->library('email', $config);
        $body = "<img src='http://125.212.192.114/ggift/data/images/other/mail-header-gg.jpg' style='width: 825px;'/><br/><br/><b>Chào mừng bạn gia nhập G-People!</b> <br /><br />Để hoàn tất quá trình đăng ký, bạn vui lòng click vào đường link dưới đây để kích hoạt tài khoản: <br /><b><a href='" . $baseurl . "active-user?username=" . $username . "&code=" . $code . "'>" . $baseurl . "active-user?username=" . $username . "&code=" . $code . "</a></b> <br /><br />Chúc bạn sẽ có những trải nghiệm thú vị cùng G-People! <br />Mọi thông tin chi tiết vui lòng liên hệ: <br /><br />- Hotline: 1900 6622 <br />- Facebook: <a target='_blank' href='https://www.facebook.com/GoldenGateRestaurantGroup'>https://www.facebook.com/GoldenGateRestaurantGroup</a> <br />- Website: <a target='_blank' href='http://ggg.com.vn/'>http://ggg.com.vn/</a><br/><br/><img src='http://125.212.192.114/ggift/data/images/other/mail-footer-gg.jpg' style='width: 825px;'/>";

        $this->email->from($this->_smtp_user, 'G-People');
        $this->email->to($username);
        $this->email->subject('Kích hoạt tài khoản G-People');
        $this->email->message($body);

        if ($this->email->send())
        {
            
        }
    }

    public function getinfoUserDb($id)
    {
        //Get parameters 
        $mobile = $this->getParamInt('mobile');
        $pass = $this->getParamString('password');
        $fbid = $this->getParamString('fbid');
        $ggid = $this->getParamString('ggid');

        if (!in_array($mobile, array(null, '', '0')))
        {
            
        }
//        if (!in_array($userid, array(null, '', '0')))
//        {
//            return (object) array('status' => 201, 'description' => 'Tham số không đúng');
//        }
//        
//        //Check đăng nhập bằng fbid hoặc ggid
//        if (in_array($pass, array(null, '', '0')))
//        {
//            //Đây là chuoi pass gui lên rỗng,hiểu là login =fb id hoặc ggid
//            if (in_array($fbid, array(null, '', '0')) && in_array($ggid, array(null, '', '0')))
//                return (object) array('status' => 201, 'description' => 'Tham số ggid,fbid không đúng');
//            //Lấy dữ liệu với ggid và fbid
//            $sql = "SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
//                    . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
//                    . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.ggid = 'ggid'";
//            $result = $this->db->query($sql);
//            $check = $result->num_rows();
//            if ($check == 0)
//            {
//                return (object) array('status' => 202, 'description' => 'Tài khoản ggid/fbid không tồn tại');
//            }
//            $data = $result->row();
//            $data->password = '';
//            return (object) array('status' => 200, 'userInfo' => $data, 'description' => 'Thông tin tài khoản');
//        }
//
//        //Check đăng nhập bằng mobile
////        $username   = $fullname ;
////        $pass_encode = md5(md5($username).md5($pass));
//        $sql = "SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
//                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
//                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.id = '$userid'";
//        $result = $this->db->query($sql);
//        $check = $result->num_rows();
//        if ($check == 0)
//        {
//            return (object) array('status' => 202, 'description' => 'Tài khoản mobile không tồn tại');
//        }
//        $passEncodeSend = md5(md5($result->username) . md5($pass));
//        $passEncode = $result->password;
//        if ($passEncodeSend != $passEncode)
//        {
//            return (object) array('status' => 203, 'description' => 'Mật khẩu không đúng');
//        }
//        $data = $result->row();
//        $data->password = '';
//        return (object) array('status' => 200, 'userInfo' => $data, 'description' => 'Thông tin tài khoản');
    }

    public function changePassDB()
    {
        $id = $this->getParamInt('id');
        $upassold = $this->getParamString('passwordold');
        $upassnew = $this->getParamString('passwordnew');
        $check=$this->db->query("SELECT * FROM member WHERE id = '$id'");
        if($check->num_rows()==0)
        {
            return (object) array('status' => 203, 'description' => 'User không tồn tại');
        }
        $result=$check->row();
        $uname=$result->username;
        $passOld=$result->password;
        $passConfirm = md5(md5($uname) . md5($upassold));
//        var_dump($passOld,$passConfirm);die;
        if($passOld != $passConfirm)
        {
             return (object) array('status' => 202, 'description' => 'Pass cũ không đúng');
        }
        $passNew=md5(md5($uname) . md5($upassnew));
        $this->db->update('member',array('password'=>$passNew),array('id'=>$id));
        return (object) array('status' => 200, 'description' => 'Bạn đã cập nhập mật khẩu thành công');
    }

    /* resend password */

    public function forGotDB()
    {
        $pass = $this->generateCodeNumber(6);
        $uname = $this->getParamString('email');
        $pass_encode = md5(md5($uname) . md5($pass));

        $qr = $this->db->query('SELECT * FROM member WHERE email = "' . strtolower($uname) . '"');
        $check = $qr->num_rows();

        if ($check > 0)
        {
            $data = array(
                'password' => $pass_encode
            );
            $query = $qr->row_object();
            $config = array(
                'protocol' => 'smtp',
                'smtp_host' => $this->_smtp_host,
                'smtp_user' => $this->_smtp_user,
                'smtp_pass' => $this->_smtp_pass,
                'mailtype' => 'html'
            );

            $this->load->library('email', $config);
            $body = "<img src='http://125.212.192.114/ggift/data/images/other/mail-header-gg.jpg' style='width: 825px;'/><br/><br/>Chào bạn, Mật khẩu G-People mới của bạn là: <b>" . $pass . "</b> <br /><br />Chúc bạn sẽ có những trải nghiệm thú vị cùng G-People! <br /><br />Mọi thông tin chi tiết vui lòng liên hệ: <br /><br />- Hotline: 1900 6622 <br />- Facebook: <a  target='_blank' href='https://www.facebook.com/GoldenGateRestaurantGroup'>https://www.facebook.com/GoldenGateRestaurantGroup</a> <br />- Website: <a target='_blank' href='http://ggg.com.vn/'>http://ggg.com.vn/</a><br/><br/><img src='http://125.212.192.114/ggift/data/images/other/mail-footer-gg.jpg' style='width: 825px;'/>";

            $this->email->from($this->_smtp_user, 'G-People');
            $this->email->to($query->email);
            $this->email->subject('Thông báo cấp lại mật khẩu G-People');
            $this->email->message($body);

            if ($this->email->send())
            {
                $this->db->update('member', $data, "email = '" . strtolower($uname) . "'");
                return (object) array('status' => 200, 'description' => 'Vui lòng kiểm tra email để lấy lại mật khẩu');
            } else
            {
                return (object) array('status' => 201, 'description' => 'Bạn không thể lấy lại mật khẩu, hãy thử lại');  // SMTP đang có lỗi
            }
        } else
        {
            return (object) array('status' => 404, 'description' => 'Tài khoản không tồn tại');
        }
    }

    public function verifyaccountDB()
    {
        $id = $this->getParamInt('id');
        $code = $this->getParamString('code');

        $sql = $this->db->query("SELECT * FROM member WHERE code = '" . $code . "' AND id = " . $id);
        if ($sql->num_rows() > 0)
        {
            $data = array(
                'active' => 1
            );
            $this->db->update('member', $data, "id = " . $id);
            return (object) array('status' => 200, 'description' => 'Kích hoạt thành công');
        } else
        {
            return (object) array('status' => 201, 'description' => 'Mã kích hoạt không đúng');
        }
    }

    public function registerFacebookDB($fbid, $email, $fullname, $avatar)
    {
        $fbid = $fbid;
        $email = $email;
        $fullname = $fullname;
        $avatar = $avatar;
        $username = $fbid;
        if (in_array($fbid, array(null, '')))
            return (object) array('status' => 201, 'description' => 'Tham số không đúng');
        
//        $username = $fbid;
        $qr = $this->db->query("SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.fbid = '$fbid'");
        $check = $qr->row()->fbid;
        if ($check == null)
        {
            if (!in_array($email, array(null, '')))
            {
                $checkEmail = $this->db->query("SELECT * FROM member WHERe email = '$email' ")->num_rows();
                if ($checkEmail > 0)
                return (object) array('status' => 204, 'description' => 'Email đã có người dùng');
                if ($this->valid_email($email))
                return (object) array('status' => 208, 'description' => 'Email không hợp lệ');
            }
            $data = array(
                'username' => $username,
                'active' => 1,
                'created' => date('Y-m-d H:i:s'),
                'fbid' => $fbid,
                'email' => $email,
                'fullname' => $fullname
            );

            $this->db->insert('member', $data);
            $id = $this->db->insert_id();
            //Upload avatar
            $avatar = $this->upAvatarDb($avatar, $id);
            if ($avatar->status == 200)
            {
                $this->db->update('member', array('avatar' => $avatar->avatar), "id ='" . $id . "'");
            }
            $infoUser = $this->db->query('SELECT * FROM member WHERE fbid = "' . $fbid . '"')->row();
            return (object) array('status' => 200, 'userInfo' => $infoUser, 'description' => 'Đăng kí thành công');
        } else
        {
            $infoUser = $qr->row();
            //$data_           = $qr->row();
            return (object) array('status' => 202, 'userInfo' => $infoUser, 'description' => 'Tài khoản fb đã được đăng kí từ trước');
        }
    }
    
    public function registerFacebookOtherDB($fbid, $email, $fullname)
    {
        $fbid = $fbid;
        $email = $email;
        $fullname = $fullname;
        $avatar = $avatar;
        $username = $fbid;
        if (in_array($fbid, array(null, '')))
            return (object) array('status' => 201, 'description' => 'Tham số không đúng');
        
//        $username = $fbid;
        $qr = $this->db->query("SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.fbid = '$fbid'");
        $check = $qr->row()->fbid;
        if ($check == null)
        {
            if (!in_array($email, array(null, '')))
            {
                $checkEmail = $this->db->query("SELECT * FROM member WHERe email = '$email' ")->num_rows();
                if ($checkEmail > 0)
                return (object) array('status' => 204, 'description' => 'Email đã có người dùng');
                if ($this->valid_email($email))
                return (object) array('status' => 208, 'description' => 'Email không hợp lệ');
            }
            $data = array(
                'username' => $username,
                'active' => 1,
                'created' => date('Y-m-d H:i:s'),
                'fbid' => $fbid,
                'email' => $email,
                'fullname' => $fullname
            );

            $this->db->insert('member', $data);
            $id = $this->db->insert_id();
            //Upload avatar
            $avatar = $this->upAvatarOtherDb($id);
            if ($avatar->status == 200)
            {
                $this->db->update('member', array('avatar' => $avatar->avatar), "id ='" . $id . "'");
            }
            $infoUser = $this->db->query('SELECT * FROM member WHERE fbid = "' . $fbid . '"')->row();
            return (object) array('status' => 200, 'userInfo' => $infoUser, 'description' => 'Đăng kí thành công');
        } else
        {
            $infoUser = $qr->row();
            //$data_           = $qr->row();
            return (object) array('status' => 202, 'userInfo' => $infoUser, 'description' => 'Tài khoản fb đã được đăng kí từ trước');
        }
    }

    public function registerGoogleDB($ggid, $email, $fullname, $avatar)
    {
        $ggid = $ggid;
        $email = $email;
        $fullname = $fullname;
        $avatar = $avatar;
        $username = $ggid;
        if (in_array($ggid, array(null, '')))
            return (object) array('status' => 201, 'description' => 'Tham số không đúng');
        
        $qr = $this->db->query("SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.ggid = '$ggid'");
        $check = $qr->row()->ggid;
//        var_dump($qr->row()->ggid);die;
        if ($check == null)
        {
            if (!in_array($email, array(null, '')))
            {
                $checkEmail = $this->db->query("SELECT * FROM member WHERe email = '$email' ")->num_rows();
                if ($checkEmail > 0)
                    return (object) array('status' => 204, 'description' => 'Email đã có người dùng');
                if ($this->valid_email($email))
                return (object) array('status' => 208, 'description' => 'Email không hợp lệ');
            }
//            echo"1";die;
            $data = array(
                'username' => $username,
                'active' => 1,
                'created' => date('Y-m-d H:i:s'),
                'ggid' => $ggid,
                'email' => $email,
                'fullname' => $fullname
            );

            $this->db->insert('member', $data);
            $id = $this->db->insert_id();
            //Upload avatar
            $avatar = $this->upAvatarDb($avatar, $id);
            if ($avatar->status == 200)
            {
                $this->db->update('member', array('avatar' => $avatar->avatar), "id ='" . $id . "'");
            }
            $infoUser = $this->db->query('SELECT * FROM member WHERE ggid = "' . $ggid . '"')->row();
//            var_dump($this->db->last_query());die;
            return (object) array('status' => 200, 'userInfo' => $infoUser, 'description' => 'Đăng kí thành công');
        } else
        {
//            echo"2";die;
            $infoUser = $qr->row();
            //$data_           = $qr->row();
            return (object) array('status' => 202, 'userInfo' => $infoUser, 'description' => 'Tài khoản fb đã được đăng kí từ trước');
        }
    }
    public function registerGoogleOtherDB($ggid, $email, $fullname)
    {
        $ggid = $ggid;
        $email = $email;
        $fullname = $fullname;
        $avatar = $avatar;
        $username = $ggid;
        if (in_array($ggid, array(null, '')))
            return (object) array('status' => 201, 'description' => 'Tham số không đúng');
        $qr = $this->db->query("SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.ggid = '$ggid'");
        $check = $qr->row()->ggid;
//        var_dump($qr->row()->ggid);die;
        if ($check == null)
        {
            if (!in_array($email, array(null, '')))
            {
                $checkEmail = $this->db->query("SELECT * FROM member WHERe email = '$email' ")->num_rows();
                if ($checkEmail > 0)
                    return (object) array('status' => 204, 'description' => 'Email đã có người dùng');
                if ($this->valid_email($email))
                return (object) array('status' => 208, 'description' => 'Email không hợp lệ');
            }
//            echo"1";die;
            $data = array(
                'username' => $username,
                'active' => 1,
                'created' => date('Y-m-d H:i:s'),
                'ggid' => $ggid,
                'email' => $email,
                'fullname' => $fullname
            );

            $this->db->insert('member', $data);
            $id = $this->db->insert_id();
            //Upload avatar
            $avatar = $this->upAvatarOtherDb($id);
            if ($avatar->status == 200)
            {
                $this->db->update('member', array('avatar' => $avatar->avatar), "id ='" . $id . "'");
            }
            $infoUser = $this->db->query('SELECT * FROM member WHERE ggid = "' . $ggid . '"')->row();
//            var_dump($this->db->last_query());die;
            return (object) array('status' => 200, 'userInfo' => $infoUser, 'description' => 'Đăng kí thành công');
        } else
        {
//            echo"2";die;
            $infoUser = $qr->row();
            //$data_           = $qr->row();
            return (object) array('status' => 202, 'userInfo' => $infoUser, 'description' => 'Tài khoản fb đã được đăng kí từ trước');
        }
    }

    private function renderQrCode($data, $path)
    {
        $this->load->library('ciqrcode');
        $time_folder = date('Ym');
        $path_mk = 'data/images/' . $path . $time_folder;
        @mkdir(UPLOAD . '/' . $path_mk, 0777);
        $file = 'images/' . $path . $time_folder . '/' . date('Ymd') . '-' . time() . '.jpg';
        $params['data'] = $data;
        $params['level'] = 'H';
        $params['size'] = 30;
        $params['savename'] = UPLOAD . '/data/' . $file;
        //die(print_r($params));
        $this->ciqrcode->generate($params);
        return $file;
    }

    private function _renderEcoupon($amount)
    {
        return $this->generateCodeNumber($amount);
    }

    private function renderEcouponOne()
    {
        $coupon = $this->_renderEcoupon(5);
        $coupon_qr = $this->_renderEcoupon(12);
        return $this->getRenderEcoupon($coupon, $coupon_qr);
    }

    private function getRenderEcoupon($ecoupon, $ecoupon_qr)
    {
        $check = $this->db->query('SELECT id FROM ecoupon_campaign WHERE code_coupon = "' . $ecoupon . '" AND code_coupon_qrcode = "' . $ecoupon_qr . '"')->num_rows();
        if ($check == 1)
        {
            $coupon = $this->_renderEcoupon(5);
            $coupon_qr = $this->_renderEcoupon(12);
            return $this->getRenderEcoupon($ecoupon, $coupon_qr);
        } else
        {
            return (object) array('coupon' => $ecoupon, 'coupon_qr' => $ecoupon_qr);
        }
    }

    public function checkCode($code_post)
    {
        $check = $this->db->query('SELECT id FROM code_user WHERE code_user = "' . $code_post . '"')->num_rows();
        if ($check == 1)
        {
            return $this->checkCode($this->generateCodeNumber(6));
        } else
        {
            return $code_post;
        }
    }

    public function getAgeGroup()
    {
        return $this->db->query('SELECT * FROM age_groups')->result_object();
    }

    public function getJob()
    {
        return $this->db->query('SELECT * FROM vn_job')->result_object();
    }

//	public function activeUser(){
//		$username = $this->getParamString('username');
//		$code = $this->getParamString('code');
//		$db = $this->db->query('SELECT active,code FROM member WHERE username = "'.$username.'" LIMIT 1');
//		if( $db->num_rows() == 0 ){
//			//return array('data' => '201', 'content' => 'Kích hoạt không thành công, tài khoản không tồn tại');
//			header('Content-Type: text/html; charset=utf-8');
//					$html ='<!DOCTYPE HTML>
//<html>
//<head>
//	<meta http-equiv="content-type" content="text/html" />
//	<meta name="author" content="try.vn" />
//	<title>Kích hoạt tài khoản G-People</title>
//</head>
//<body>
//<div style="margin: 0 auto;width: 1000px;height:500px;text-align: center;font-family:Arial;">
//    <h1 style="color: #241E1E;">Kích hoạt tài khoản G-People</h1>
//    <h3 style="color: #8C5C5C;">Trạng thái : Kích hoạt không thành công, tài khoản không tồn tại</h3>
//</div>
//</body>
//</html>';
//return $html;
//		}else{
//			$code_db = $db->row()->code;
//			if ( $code_db == $code ){
//				$active_db = $db->row()->active;
//				if( $active_db == 0 ){
//					$this->db->update('member', array('active' => 1 ), "username = '".$username."'");
//					//return array('data' => '200', 'content' => 'Kích hoạt thành công');
//					header('Content-Type: text/html; charset=utf-8');
//					$html ='<!DOCTYPE HTML>
//<html>
//<head>
//	<meta http-equiv="content-type" content="text/html" />
//	<meta name="author" content="try.vn" />
//	<title>Kích hoạt tài khoản G-People</title>
//</head>
//<body>
//<div style="margin: 0 auto;width: 1000px;height:500px;text-align: center;font-family:Arial;">
//    <h1 style="color: #241E1E;">Kích hoạt tài khoản G-People</h1>
//    <h3 style="color: #8C5C5C;" >Tên tài khoản : '.$username.'</h3>
//    <h3 style="color: #8C5C5C;">Mã kích hoạt : '.$code_db.'</h3>
//    <h3 style="color: #8C5C5C;">Trạng thái : Kích hoạt thành công</h3>
//</div>
//</body>
//</html>';
//return $html;
//				}else{
//					//return array('data' => '202', 'content' => 'Tài khoản đã được kích hoạt');
//									header('Content-Type: text/html; charset=utf-8');
//									$html ='<!DOCTYPE HTML>
//<html>
//<head>
//	<meta http-equiv="content-type" content="text/html" />
//	<meta name="author" content="try.vn" />
//	<title>Kích hoạt tài khoản G-People</title>
//</head>
//<body>
//<div style="margin: 0 auto;width: 1000px;height:500px;text-align: center;font-family:Arial;">
//    <h1 style="color: #241E1E;">Kích hoạt tài khoản G-People</h1>
//    <h3 style="color: #8C5C5C;" >Tên tài khoản : '.$username.'</h3>
//    <h3 style="color: #8C5C5C;">Mã kích hoạt : '.$code_db.'</h3>
//    <h3 style="color: #8C5C5C;">Trạng thái : Tài khoản đã được kích hoạt</h3>
//</div>
//</body>
//</html>';
//return $html;
//				}
//			}else{
//				//return array('data' => '203', 'content' => 'Kích hoạt không thành công, mã kích hoạt không tồn tại');
//													header('Content-Type: text/html; charset=utf-8');
//													$html ='<!DOCTYPE HTML>
//<html>
//<head>
//	<meta http-equiv="content-type" content="text/html" />
//	<meta name="author" content="try.vn" />
//	<title>Kích hoạt tài khoản G-People</title>
//</head>
//<body>
//<div style="margin: 0 auto;width: 1000px;height:500px;text-align: center;font-family:Arial;">
//    <h1 style="color: #241E1E;">Kích hoạt tài khoản G-People</h1>
//    <h3 style="color: #8C5C5C;" >Tên tài khoản : '.$username.'</h3>
//    <h3 style="color: #8C5C5C;">Mã kích hoạt : '.$code_db.'</h3>
//    <h3 style="color: #8C5C5C;">Trạng thái : Kích hoạt không thành công, mã kích hoạt không tồn tại</h3>
//</div>
//</body>
//</html>';
//return $html;
//			}
//		}
//	}

    public function upAvatarDb($img, $id)
    {
        $result=$this->db->query("SELECT * FROM member WHERE id = '$id'");
        $checkId=$result->num_rows();
        if($checkId == 0) return (object) array('status' => 202, 'description' => "id không tồn tại");
        if ($img == null)
            return (object) array('status' => 201, 'description' => 'Ảnh ko được để trống');
        // Decode Image
//        $img="/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQQDxUPDxQVEBQPEA4PDxAQDxAPDg8OFBEXFhQUFRQYHCsgGBolHBQUJDEhJikrLi4uFyAzODMsNyouLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIAMoA+QMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAAAgYDBAUBB//EAEsQAAEDAgMFAgkHCAcJAAAAAAEAAgMEEQUhMQYSQVFhE3EUIjJCUoGRobEHM1NicpLBNENzgqKy0fAVI1RjdLPhFiQlRIOTlKPC/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/APuKIiAiIgIiICIiAiLj4hj7GO7KFpqJdNxnktP136D3lB2FysQ2ip4DuvkDnadnGDI+/IhunrsuTLSz1H5VKWtP5iA7jLcnO1d3ZhbVHQRwi0TGs4XA8b72qDE/aKok/J6RwB0fUvbF+xqfatd7sQk1nhp+kMHaH/2Lq2SyDiOwqod5ddUH9GGQj2BY3bPvP/O1v/k/6LvWXiDgHBJx5GIVQ+25so9hUexxOP5uujm5NqKVrB95lyu+QoFBxBtPiMH5RQsqWjyn0c3jeqJ/jFbmHfKPRSP7KZ7qOXK8VWwwOBP1j4vvW6Vq4hQRVDdyeNkzfRkY14HdfQ9yC0xTNeAWkOBzBBuCFNfK37ISUpMmD1T6Q6+DSl09C855bpu5l76i5W7h3yjPp5G0+NQGje47rKlpL6GY/Vk809DpxIQfR0WGmqmyNDmODg4Aggggg6EHisyAiIgIiICIiAiIgIiICIiAiIgLFVVLYmF8jg1o1J9wA4nooV1Y2Fhe85aADynO4NA5ritgdO8TVHD5qHVsY5nmf56IIzTy1fpQQHgMp5R1Pmju9+i2aalbE3djaGjpx7zxWxZLII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efDQcSfoGH0QjaAAgy0sAY2wWdEQEREBERAREQEREBERAXM2hwGCvgdT1UYkY7nk5ruDmu1a4cwumiD5DXx1mC+LU79fQN8iqaN6rpGcpm+e0el04ZNVhw2siqIxNA9srHaPYbi/I8j0Oavb2AixzXz/HPk4DZTV4TKaCc5vYwB1JP0kh09Y53tdB0RGpiNVP/a2aiPZ4zSup7ZeGUzXT0T+pt4zO7M9Fa8LxCGpZ2lNKyZvpRva+3QgZg9CgyCNTDFmDFMMQYQxSEazBikGIMQYpBiyhikGoMQYphqyWXjnAC5IA5k2QeBq9OQucuZOi5OKbRwwZF13HRgu557mDxj32t1XBkq6utNmA08Z4mxmI6cGeq56hB08d2hjiIjjBlmt4sbTZwB4uPmN6nM2yBstDC8ClqZBPVHeI8hgFo4geDR8Scz7LdrAdlGQi5FyTdxObnOOpJOp6q0QwhosAgwUNE2MWAW2iICIiAiIgIiICIiAiIgIiICIiAiIgxT0zXgteA4EWIIuCFR8Z+S2kleZqcPo5c7S0jzA4E9Bl7lfUQfLjguM0fzNVHWsGjKuGzwP0jM3HvKkza2tiNqrDjlq+nmDge5lifevpxWvUMHIewIKDH8oEP5yCpi570Tbe9wWy3b6jPF472sH/ANLvVULfRb90LmyQN9Fv3Qg1v9uaY+Tvn1M/BxUH7atOUcMjj9h/4tA96244G+i37oXQpoW+iPuhBXjjtZLlFBuX4vIbb1Dev7QvWYJVzm80paDqIrs/auXe9XSnYOQ9gW4wIKxhWyEUWdhc5knMk8yeKsUFG1gsAthEBERAREQEREBERAREQf/Z";
        //DECODE IMG base 64
        $img = base64_decode($img);
        header('Content-Type: bitmap; charset=utf-8');
        $path = UPLOAD . '/data/images/avatar/';
        //CREATE FILE NAME
        while (true)
        {
            $filename = str_replace('.', '', uniqid('avatar_', true));
            if (!file_exists($path . $filename))
                break;
        }
//        chmod(UPLOAD . '/data/images/avatar', 0777);
        $file = fopen($path . $filename . '.jpg', 'wb');
        if ($file == FALSE)
        {
            return (object) array('status' => 201, 'description' => "Update avatar thất bại");
        }
//        var_dump($file);die;
        // Create File
        fwrite($file, $img);
        fclose($file);
        
        $avatarOld=$result->row()->avatar;
        if(!in_array($avatarOld, array(null, '','0')))
        {
            @unlink(PROJECT_PATH.'/data/'.$avatarOld);
        }
        //SAVE INTO DATABASE
        $this->db->update('member', array('avatar' => '/images/avatar/' . $filename . '.jpg'), "id ='" . $id . "'");
        return (object) array('status' => 200, 'description' => "Update avatar thành công", 'avatar' => '/images/avatar/' . $filename . '.jpg');
    }

    public function upAvatarOtherDb($id)
    {
        $result=$this->db->query("SELECT * FROM member WHERE id = '$id'");
        $checkId=$result->num_rows();
        if($checkId == 0) return (object) array('status' => 202, 'description' => "id không tồn tại");
        $path1 = 'images/avatar/';
        @mkdir(PROJECT_PATH . '/data/' . $path1, 777);
//                    var_dump(PROJECT_PATH . '/data/' . $path1);die;
        $config['upload_path'] = '../data/' . $path1;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2000';
        $config['max_width'] = '1000'; //10240';
        $config['max_height'] = '1000'; //'7680';
        $config['encrypt_name'] = TRUE; // TRUE/FALSE (boolean)
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('img'))
        {
            return (object) array('status' => 201, 'description' => "Update avatar thất bại",'description'=>$this->upload->display_errors());
        } else
        {
            $data_img = $this->upload->data();
            $pathImg=$path1 . $data_img['file_name'];
            $this->db->update('member', array('avatar' => $pathImg), "id ='" . $id . "'");
            $avatarOld=$result->row()->avatar;
            if (!in_array($avatarOld, array(null, '', '0')))
            {
                @unlink(PROJECT_PATH . '/data/' . $avatarOld);
            }
            return (object) array('status' => 200, 'description' => "Update avatar thành công", 'avatar' => $pathImg);
        }
    }
    public function activeMobileDb($mobile, $code)
    {
        $query = "SELECT m.*,Count(Distinct eu.id) as number_coupon ,Count(Distinct ru.id) as number_like "
                . "FROM member as m LEFT JOIN ecoupon_user as eu ON m.id=eu.user_id "
                . "LEFT JOIN restaurant_user as ru ON m.id=ru.user_id WHERE m.mobile = $mobile AND m.code = $code";
        $data = $this->db->query($query);
        if ($data->row()->id == null)
        {
            return (object) array('status' => 201, 'description' => "Sai mã kích hoạt/Sai số điện thoại");
        } else
        {
            $userInfo = $data->row();
            if ($userInfo->active == 1)
                return (object) array('status' => 202, 'description' => "Đã kích hoạt từ trước rồi", 'userInfo' => $userInfo);
            $this->db->update('member', array('active' => 1), "id = '" . $data->row()->id . "'");
            $userInfo->active = 1;
            $userInfo->password = "";
            return (object) array('status' => 200, 'description' => "Kích hoạt thành công", 'userInfo' => $userInfo);
        }
//        return (object)array('status' => 200, 'description' => "Kích hoạt thành công",'userInfo'=>$userInfo);
    }

    public function getUserSmsDb($stt)
    {
        $stt = $stt ? $stt : 0;
        $query = "SELECT * FROM user_active WHERE status = 0 ANd phone IS NOT NULL AND substring(phone, 1, 1) = 0 AND number_send < 3 ORDER BY id ASC Limit " . $stt . ",100";
        $result = $this->db->query($query);
        if ($result->num_rows() == 0)
            return (object) array('status' => 201, 'description' => "Không tìm thấy kết quả ");
        $data = $result->result_object();
        return (object) array('status' => 200, 'description' => "Tìm thấy kết quả", 'data' => $data);
    }

    //Xảy ra khi khach hang reset lại pass sẽ gửi đến tin nhắn...gửi đến api nay check sau đó bắn tin nhắn(status:0 la gửi,1 là ko gửi)
//     public function resetSmsPasswordDb($phone)
//     {
//        //Lấy thông tin bảng user_active để check
//        $query = "SELECT * FROM user_active WHERE phone= '$phone'";
//        $result = $this->db->query($query);
//        if ($result->num_rows() == 0)
//            return (object) array('status' => 202, 'description' => "Không tìm thấy số điện thoại");
//        $data = $result->row();
//        $id = $data->id;
//        $idSave= $id;
//        //Reset lại số lần gửi sms nếu khác ngày
//        if (date('Y-m-d') != $data->date)
//        {
//            $arrayUpdate = array(
//                'number_send' => 0,
//                'date' => date('Y-m-d'),
//            );
//            $this->db->update('user_active', $arrayUpdate, "id ='" . $id . "'");
//            //Lấy lại dữ liệu data
//            $data = $this->db->query("SELECT * FROM user_active WHERE id = '$id'")->row();
//        }
//        
//        //CHeck nếu quá 3 lần 1 ngày thì ko đc gửi
//        $numberSend=$data->number_send;
//        $date=$data->date;
//        if($numberSend >= 3 AND date('Y-m-d') == $date )
//        {
//            return (object)array('status' => 201, 'description' => "Bạn chỉ gửi sms tối đa 1 ngày 3 lần");
//        }
//        
//        //Update password bảng user_member
//        $query = "SELECT * FROM member WHERE username= '$phone'";
//        $result = $this->db->query($query);
//        if ($result->num_rows() == 0)
//            return (object) array('status' => 202, 'description' => "Không tìm thấy số điện thoại");
//        $data = $result->row();
//        $id = $data->id;
//        $username = $data->username;
//        $pass = $this->generateCodeNumber(5);
//        $pass_encode = md5(md5($username) . md5($pass));
//        $this->db->update('member', array('password' => $pass_encode), "id ='" . $id . "'");
//        
//        //update lại number send bảng user_active
//        $numberSend=$numberSend+1;
//        $arrayUpdate=array(
//            'number_send' => $numberSend,
//        );
//        $this->db->update('user_active',$arrayUpdate, "id ='" . $idSave . "'");
//        return (object) array('status' => 200, 'description' => "Update thành công", 'password' => $pass);
//    }

    public function resetSmsPasswordDb($phone)
    {
        $query = "SELECT * FROM member WHERE username= '$phone'";
        $result = $this->db->query($query);
        if ($result->num_rows() == 0)
            return (object) array('status' => 202, 'description' => "Không tìm thấy so dien thoai");
        $data = $result->row();
        //         var_dump($data);die;
        $id = $data->id;
        $username = $data->username;
        $pass = $this->generateCodeNumber(5);
        $pass_encode = md5(md5($username) . md5($pass));
        $this->db->update('member', array('password' => $pass_encode), "id ='" . $id . "'");
        return (object) array('status' => 200, 'description' => "Update thành công", 'password' => $pass);
    }

    //Xay ra khi mr nhat gửi code active qua điện thoại đồng thời gọi cái này để update
    public function updateUserSmsDb($phone, $code_active)
    {
        $query = "SELECT * FROM user_active WHERE phone= '$phone' AND code_active= '$code_active' ";
        $result = $this->db->query($query);
        if ($result->num_rows() == 0)
            return (object) array('status' => 202, 'description' => "Không tìm thấy");
        $data = $result->row();
        $id = $data->id;

        //Reset lại nếu khác ngày
        if (date('Y-m-d') != $data->date)
        {
            $arrayUpdate = array(
                'number_send' => 0,
                'date' => date('Y-m-d'),
            );
            $this->db->update('user_active', $arrayUpdate, "id ='" . $id . "'");
            $data = $this->db->query("SELECT * FROM user_active WHERE id = '$id'")->row();
        }

        //CHeck nếu quá 3 lần 1 ngày thì ko đc gửi
        $numberSend = $data->number_send;
        $date = $data->date;

        if ($numberSend >= 3 AND date('Y-m-d') == $date)
        {
            return (object) array('status' => 201, 'description' => "Bạn chỉ gửi sms tối đa 1 ngày 3 lần");
        }

        //Cộng vào 
        $numberSend = $numberSend + 1;
        $arrayUpdate = array(
            'status' => 1,
            'number_send' => $numberSend,
            'date' => date('Y-m-d'),
        );
        $this->db->update('user_active', $arrayUpdate, "id ='" . $id . "'");
        return (object) array('status' => 200, 'description' => "Update thành công");
    }
    
    public function editAvatarDb($img, $id)
    {
        $result=$this->db->query("SELECT * FROM member WHERE id = '$id'");
        $checkId=$result->num_rows();
        if($checkId == 0) return (object) array('status' => 202, 'description' => "id không tồn tại");
        if ($img == null)
            return (object) array('status' => 201, 'description' => 'Ảnh ko được để trống');
        
        // Decode Image
//        $img="/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQQDxUPDxQVEBQPEA4PDxAQDxAPDg8OFBEXFhQUFRQYHCsgGBolHBQUJDEhJikrLi4uFyAzODMsNyouLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIAMoA+QMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAAAgYDBAUBB//EAEsQAAEDAgMFAgkHCAcJAAAAAAEAAgMEEQUhMQYSQVFhE3EUIjJCUoGRobEHM1NicpLBNENzgqKy0fAVI1RjdLPhFiQlRIOTlKPC/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/APuKIiAiIgIiICIiAiLj4hj7GO7KFpqJdNxnktP136D3lB2FysQ2ip4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S0jzA4E9Bl7lfUQfLjguM0fzNVHWsGjKuGzwP0jM3HvKkza2tiNqrDjlq+nmDge5lifevpxWvUMHIewIKDH8oEP5yCpi570Tbe9wWy3b6jPF472sH/ANLvVULfRb90LmyQN9Fv3Qg1v9uaY+Tvn1M/BxUH7atOUcMjj9h/4tA96244G+i37oXQpoW+iPuhBXjjtZLlFBuX4vIbb1Dev7QvWYJVzm80paDqIrs/auXe9XSnYOQ9gW4wIKxhWyEUWdhc5knMk8yeKsUFG1gsAthEBERAREQEREBERAREQf/Z";
        //DECODE IMG base 64
        $img = base64_decode($img);
        header('Content-Type: bitmap; charset=utf-8');
        $path = UPLOAD . '/data/images/avatar/';
        //CREATE FILE NAME
        while (true)
        {
            $filename = str_replace('.', '', uniqid('avatar_', true));
            if (!file_exists($path . $filename))
                break;
        }
//        chmod(UPLOAD . '/data/images/avatar', 0777);
        $file = fopen($path . $filename . '.jpg', 'wb');
        if ($file == FALSE)
        {
            return (object) array('status' => 201, 'description' => "Update avatar thất bại");
        }
//        var_dump($file);die;
        // Create File
        fwrite($file, $img);
        fclose($file);
        $avatarOld=$result->row()->avatar;
        @unlink(PROJECT_PATH.'/data/'.$avatarOld);
        //SAVE INTO DATABASE
        $this->db->update('member', array('avatar' => '/images/avatar/' . $filename . '.jpg'), "id ='" . $id . "'");
        return (object) array('status' => 200, 'description' => "Update avatar thành công", 'avatar' => '/images/avatar/' . $filename . '.jpg');
    }
    
    public function deleteAvatarDb($id)
    {
        $result=$this->db->query("SELECT * FROM member WHERE id = '$id'");
        $checkId=$result->num_rows();
        if($checkId == 0) return (object) array('status' => 202, 'description' => "id không tồn tại");
        $avatarOld=$result->row()->avatar;
        if(!in_array($avatarOld, array(null, '','0')))
        {
            @unlink(PROJECT_PATH.'/data/'.$avatarOld);
        }
        //SAVE INTO DATABASE
        $this->db->update('member', array('avatar' => ''), "id ='" . $id . "'");
        return (object) array('status' => 200, 'description' => "Delete avatar thành công", 'avatar' => '/images/avatar/' . $filename . '.jpg');
    }
    public function editAvatarOtherDb($id)
    {
        $result=$this->db->query("SELECT * FROM member WHERE id = '$id'");
        $checkId=$result->num_rows();
        if($checkId == 0) return (object) array('status' => 202, 'description' => "id không tồn tại");
        $path1 = 'images/avatar/';
        @mkdir(PROJECT_PATH . '/data/' . $path1, 777);
//                    var_dump(PROJECT_PATH . '/data/' . $path1);die;
        $config['upload_path'] = '../data/' . $path1;
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2000';
        $config['max_width'] = '1000'; //10240';
        $config['max_height'] = '1000'; //'7680';
        $config['encrypt_name'] = TRUE; // TRUE/FALSE (boolean)
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload('img'))
        {
            return (object) array('status' => 201, 'description' => "Update avatar thất bại",'description'=>$this->upload->display_errors());
        } else
        {
            $data_img = $this->upload->data();
            $pathImg=$path1 . $data_img['file_name'];
            $this->db->update('member', array('avatar' => $pathImg), "id ='" . $id . "'");
            $avatarOld=$result->row()->avatar;
             if (!in_array($avatarOld, array(null, '', '0')))
            {
                @unlink(PROJECT_PATH . '/data/' . $avatarOld);
            }
            return (object) array('status' => 200, 'description' => "Update avatar thành công", 'avatar' => $pathImg);
        }
    }
}
